package com.cloud.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.Set;

public class ThreadMapUtils extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(ThreadMapUtils.class);

    private Set<Point> set;

    public ThreadMapUtils(Set<Point> set) {
        this.set = set;
    }

    public void run(String dir, int zoom, String mapPath, boolean overwrite, int success, int error, int finishThread) {
        File base = new File(dir, zoom + "");
        for (Point point : set) {
            int x = point.x;
            int y = point.y;
            File path = new File(base, x + "");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, y + ".png");
            if (!file.exists() || overwrite) {
                String url = String.format(mapPath, (int) (Math.random() * 3), x, y, zoom);
                boolean b = save(url, file);
                if (b) {
                    success++;
                } else {
                    error++;
                }
            }
        }
        ++finishThread;
    }

    private boolean save(String path, File file) {
        InputStream is = null;
        OutputStream os = null;
        try {
            os = Files.newOutputStream(file.toPath());
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            is = conn.getInputStream();
            //判断是否未获取到
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                String head = new String(bytes);
                if (head.contains("<!DOCTYPE html>")) {
                    os.close();
                    return save(path, file);
                }
                os.write(bytes, 0, len);
            }
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage() + ",url:" + path);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    logger.error("输出流关闭失败:", e.getMessage());
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error("输入流关闭失败:", e.getMessage());
                }
            }
        }
        return false;
    }

}
